package com.demo2do.boyle.client.web.controller.customer;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo2do.boyle.client.Constant;
import com.demo2do.boyle.client.service.CustomerMessageService;
import com.demo2do.boyle.client.service.CustomerService;
import com.demo2do.boyle.client.service.CustomerTagService;
import com.demo2do.boyle.client.service.DataService;
import com.demo2do.boyle.client.service.TagService;
import com.demo2do.boyle.client.service.WalletService;
import com.demo2do.boyle.common.entity.customer.Customer;
import com.demo2do.boyle.common.entity.customer.CustomerTag;
import com.demo2do.boyle.common.entity.customer.message.CustomerMessage;
import com.demo2do.boyle.common.entity.customer.wallet.Wallet;
import com.demo2do.boyle.common.entity.customer.wallet.WalletRecord;
import com.demo2do.boyle.common.entity.customer.wallet.Withdrawal;
import com.demo2do.boyle.common.entity.customer.wallet.WithdrawalType;
import com.demo2do.boyle.common.entity.system.tag.Type;
import com.demo2do.core.entity.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.resolver.Page;
import com.demo2do.core.web.resolver.Secure;

/**
 * 
 * @author Wilson
 */
@Controller
@RequestMapping("")
public class CustomerController {

    private static final Logger logger = LoggerFactory.getLogger(CustomerController.class);
    
    @Autowired
    private CustomerService customerService;

    @Autowired
    private WalletService walletService;
    
    @Autowired
    private DataService<Withdrawal> withdrawalService;

    @Autowired
    private TagService tagService;

    @Autowired
    private CustomerTagService customerTagService;
    
    @Autowired
    private CustomerMessageService customerMessageService;
    
    /**
     * 
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/customers/profile")
    public String getProfile(@Secure(property="id") Integer customerId, Page page) {

        Result result = new Result();
        
        try {
        	
        	Customer customer = customerService.load(Customer.class, customerId);
        	int messageCount = customerMessageService.messageCount(customer);
        	result.data("customer", customer).data("messageCount", messageCount);
            result.success();

        } catch (Exception e) {

            logger.info("getProfile()", e);
            result.fail().message("服务器异常");

        }

        return JsonUtils.toJsonString(result);
    }
    
    
    /**
     * List system tags by tagType
     * 
     * @param tagType
     * @return
     */
    @RequestMapping("/system/tags")
    @ResponseBody
    public String getSystemTags(@RequestParam("tagType") Type tagType) {
    	Result result = new Result();

        try {
            if(tagType.equals(Type.INTEREST)) {
            	result.data("systemTags" , tagService.listInterestTag()).success();
            }else if(tagType.equals(Type.LIFE)) {
            	result.data("systemTags", tagService.listLifeTag()).success();
            }

        } catch (Exception e) {
            logger.info("getTags()", e);
            result.fail().message("服务器异常");
        }
        
        return JsonUtils.toJsonString(result);
    }
    

    /**
     * 
     * @param customerId
     * @param tagType
     * @return
     */
    @ResponseBody
    @RequestMapping("/customers/{id}/tags")
    public String getTags(
            @Secure(property="id") Integer customerId,
            @RequestParam("tagType") Type tagType) {

        Result result = new Result();

        try {
        	
        	Customer customer = customerService.load(Customer.class, customerId);

            if(tagType.equals(Type.INTEREST)) {
            	result.data("customerTags", customerTagService.listCustomerInterestTag(customer.getCustomerTag().getInterestTagCodes())).success();
            }else if(tagType.equals(Type.LIFE)) {
            	result.data("customerTags", customerTagService.listCustomerLifeTag(customer.getCustomerTag().getLifeTagCodes())).success();
            }

        } catch (Exception e) {

            logger.info("getTags()", e);
            result.fail().message("服务器异常");

        }
        
        return JsonUtils.toJsonString(result);
    }
    
    @ResponseBody
    @RequestMapping("/customers/{id}/messages")
    public String getMessgaes(@Secure(property = "id") Integer customerId) {
    	Result result = new Result();
    	
    	try {
    		
    		Customer customer = customerService.load(Customer.class, customerId);
    		
    		List<CustomerMessage> customerMessages = customerMessageService.list(customer);
    		
    		customerService.updateMessageStaus(customerMessages);
    		
    		result.success().data("customerMessages", customerMessages);
    		
    	} catch (Exception e) {
    		logger.info("getMessages()", e);
    		result.fail().message("服务器异常");
    	}
    	
    	return JsonUtils.toJsonString(result);
    }

    /**
     * list all records of wallet and get wallet info
     * 
     * @param customerId
     * @return
     */
    @ResponseBody
    @RequestMapping("/customers/{customerId}/wallet-records")
    public String listWalletRecords(@Secure(property="id") Integer customerId, Page page) {

        Result result = new Result();

        try {
        	
            Wallet wallet = walletService.load(customerId);
            List<WalletRecord> walletRecords = walletService.listRecords(wallet, page);
            result.success()
                  .data("wallet", wallet)
                  .data("walletRecords", walletRecords);
        } catch (Exception e) {

            logger.info("listWalletRecords()", e);
            result.fail().message("服务器异常");

        }
        return JsonUtils.toJsonString(result);
    }

    /**
     * 
     * @param customerId
     * @param tagCode
     * @param tagType
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/customers/{id}/add-tag", method=RequestMethod.POST)
    public String addTag(
    		@Secure(property="id") Integer customerId,
            @RequestParam("tagCode") int tagCode,
            @RequestParam("tagType") Type tagType) {

        Result result = new Result();

        try {

        	if(tagType.equals(Type.INTEREST)) {
        		CustomerTag customerTag = customerTagService.addInterestTag(customerId, tagCode);
        		result.data("customerTags", customerTagService.listCustomerInterestTag(customerTag.getInterestTagCodes()))
        			  .success();
        	}else if (tagType.equals(Type.LIFE)) {
        		CustomerTag customerTag = customerTagService.addLifeTag(customerId, tagCode);
        		result.data("customerTags", customerTagService.listCustomerLifeTag(customerTag.getLifeTagCodes()))
        			  .success();
        	}
        	
        } catch (Exception e) {

            logger.info("addTag()", e);
            result.fail().message("服务器异常");

        }

        return JsonUtils.toJsonString(result);
       
    }

    /**
     * 
     * @param customerId
     * @param tagCode
     * @param tagType
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/customers/{customerId}/delete-tag", method=RequestMethod.POST)
    public String deleteTag(
    		@Secure(property="id") Integer customerId,
    		@RequestParam("tagCode") int tagCode,
    		@RequestParam("tagType") Type tagType) {

        Result result = new Result();

        try {
        	
        	if(tagType.equals(Type.INTEREST)) {
        		CustomerTag customerTag = customerTagService.deleteIntergestTag(customerId, tagCode);
        		result.data("customerTags", customerTagService.listCustomerInterestTag(customerTag.getInterestTagCodes()))
        			  .success();
        	}else if (tagType.equals(Type.LIFE)) {
        		CustomerTag customerTag = customerTagService.deleteLifeTag(customerId, tagCode);
        		result.data("customerTags", customerTagService.listCustomerLifeTag(customerTag.getLifeTagCodes()))
        			  .success();
        	}
        	
        } catch (Exception e) {

            logger.info("deleteTag()", e);
            result.fail().message("服务器异常");

        }

        return JsonUtils.toJsonString(result);
       
    }

    /**
     * withdraw with payment info
     * 
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/customers/{customerId}/withdraw", method=RequestMethod.POST)
    public String withdraw(@Secure(property="id") Integer customerId,
    					   @RequestParam("account") String account,
    					   @RequestParam("name") String name,
    					   @RequestParam("money") Integer money) {

        Result result = new Result();
        try {
        	
        	Customer customer = customerService.load(Customer.class, customerId);
        	
        	Wallet wallet = walletService.load(customerId);
        	
        	if(wallet.getBalance() < money*100 || wallet.getBalance() - wallet.getFrozenAmount() < money*100) {
        		if (wallet.getBalance() < money*100) {
        			result.fail().message("您的账户可取现余额不足！");
				} else {
					result.fail().message("您已申请提现 "+ wallet.getFrozenAmount()/100 + " 元，可取现余额不足！");
				}
        	}else {
        		Withdrawal withdrawal = new Withdrawal(account, name, money*100, WithdrawalType.ALIPAY, customer);
            	withdrawalService.save(withdrawal.initialize());
            	customerMessageService.create(customer, Constant.CUSTOMER_MESSAGE_WITHDRAWAL_CREATE, com.demo2do.boyle.common.entity.customer.message.Type.WITHDRAWAL);
            	// add frozenAmount to wallet
            	walletService.update(wallet.addFrozenAmount(money));
            	
            	result.success().message("提现申请成功");
        	}

        } catch (Exception e) {
            logger.info("withdraw()", e);
            result.fail().message("服务器异常");
        }

        return JsonUtils.toJsonString(result);
    }

}
